﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Tasks;
using Microsoft.Xna.Framework.Media;
using System.IO;

namespace rateitorhateit
{
    public partial class TakeAPic : PhoneApplicationPage
    {
        // Camera capture task
        CameraCaptureTask cameraCaptureTask;
        string newPhotoName;
        // Using a stream reference to upload the image to blob storage.
        Stream imageStream = null;

        public TakeAPic()
        {
            InitializeComponent();

            cameraCaptureTask = new CameraCaptureTask();
            cameraCaptureTask.Completed += new EventHandler<PhotoResult>(cameraCaptureTask_Completed);
            cameraCaptureTask.Completed += cameraCaptureTask_Completed; 
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // Launch the built-in camera app.
                cameraCaptureTask.Show();
            }
            catch (Exception err)
            {
                MessageBox.Show("An error occurred: " + err.Message);
            }
        }

        void cameraCaptureTask_Completed(object sender, PhotoResult e)
        {
            imageStream = e.ChosenPhoto;

            if (e.TaskResult == TaskResult.OK)
            {
                // Save the photo on a different thread.
                this.Dispatcher.BeginInvoke(delegate()
                {
                    // Create the file name.
                    newPhotoName = Path.GetFileNameWithoutExtension(e.OriginalFileName) + "_edited.jpg";

                    // Save the photo to the media library.
                    MediaLibrary library = new MediaLibrary();
                    library.SavePictureToCameraRoll(newPhotoName, e.ChosenPhoto);

                    MessageBox.Show("Capture successful. Tap Start, view the photo in the Camera Roll, then in the app bar, tap Open.");
                });
            }
        }
        
    }
}